package org.dromara.business.modules.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.modules.merchant.domain.BuMerchant;
import org.dromara.business.modules.merchant.domain.bo.BuMerchantBo;
import org.dromara.business.modules.merchant.domain.vo.BuMerchantVo;
import org.dromara.business.modules.merchant.mapper.BuMerchantMapper;
import org.dromara.business.modules.merchant.service.IBuMerchantService;
import org.dromara.business.modules.message.domain.BuMessage;
import org.dromara.business.modules.message.mapper.BuMessageMapper;
import org.dromara.common.core.constant.RoleConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.UserService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.BaseEntity;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.system.domain.bo.AuditBo;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商户信息Service业务层处理
 *
 * @author ckk
 * @date 2025-11-01
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BuMerchantServiceImpl implements IBuMerchantService {

    private final BuMerchantMapper baseMapper;
    private final ISysUserService sysUserService;
    private final BuMessageMapper buMessageMapper;
    private final UserService userService;


    /**
     * 查询商户信息
     *
     * @param id 主键
     * @return 商户信息
     */
    @Override
    public BuMerchantVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询商户信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商户信息分页列表
     */
    @Override
    public TableDataInfo<BuMerchantVo> queryPageList(BuMerchantBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BuMerchant> lqw = buildQueryWrapper(bo);
        Page<BuMerchantVo> result = baseMapper.queryPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的商户信息列表
     *
     * @param bo 查询条件
     * @return 商户信息列表
     */
    @Override
    public List<BuMerchantVo> queryList(BuMerchantBo bo) {
        LambdaQueryWrapper<BuMerchant> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BuMerchant> buildQueryWrapper(BuMerchantBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BuMerchant> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BuMerchant::getId);
        lqw.like(StringUtils.isNotBlank(bo.getMerchantName()), BuMerchant::getMerchantName, bo.getMerchantName());
        lqw.like(StringUtils.isNotBlank(bo.getCreditCode()), BuMerchant::getCreditCode, bo.getCreditCode());
        lqw.eq(StringUtils.isNotBlank(bo.getMerchantCategory()), BuMerchant::getMerchantCategory, bo.getMerchantCategory());
        lqw.like(StringUtils.isNotBlank(bo.getContactPerson()), BuMerchant::getContactPerson, bo.getContactPerson());
        lqw.like(StringUtils.isNotBlank(bo.getContactPhone()), BuMerchant::getContactPhone, bo.getContactPhone());
        lqw.eq(bo.getStatus() != null, BuMerchant::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增商户信息
     *
     * @param bo 商户信息
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BuMerchantBo bo) {
        BuMerchant add = MapstructUtils.convert(bo, BuMerchant.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商户信息
     *
     * @param bo 商户信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BuMerchantBo bo) {
        BuMerchant update = MapstructUtils.convert(bo, BuMerchant.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    @Transactional(rollbackFor = Exception.class)
    public void validEntityBeforeSave(BuMerchant entity) {
        boolean exists = new LambdaQueryChainWrapper<>(baseMapper)
            .and(q -> q.eq(BuMerchant::getMerchantName, entity.getMerchantName())
                .or().eq(BuMerchant::getCreditCode, entity.getCreditCode()))
            .ne(entity.getId() != null, BuMerchant::getId, entity.getId())
            .exists();
        if (exists) {
            throw new RuntimeException("商户名称或社会信用代码认证信息已存在，请勿重复使用，可更换商户后再次尝试认证");
        }
        entity.setStatus(1);
        BuMessage buMessage = new BuMessage();
        String title = "【商户入驻】用户 " + entity.getContactPerson() + "（" + entity.getContactPhone() + "）提交入驻申请，请及时审核。";
        buMessage.setTitle(title);
        buMessage.setContent(title);
        buMessage.setBusinessSign("merchant");
        buMessage.setBusinessId(entity.getId().toString());
        buMessage.setSendTime(new Date());
        buMessage.setIsRead(0);
        buMessage.setIsDeleted(0);
        List<Long> userIds = userService.selectUserIdsByRoleIds(List.of(RoleConstants.ADMIN));
        userIds.forEach(userId -> {
            buMessage.setReceiverId(userId);
            buMessageMapper.insert(buMessage);
        });

        SseMessageDto dto = new SseMessageDto();
        dto.setMessage(title);
        dto.setUserIds(userIds);
        SseMessageUtils.publishMessage(dto);

    }

    /**
     * 校验并批量删除商户信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 判断是否为商户
     *
     * @return {@link Integer 0-已审核，1-待审核,-1-未注册}
     */
    @Override
    public Integer isMerchant() {
        BuMerchant merchant = baseMapper.selectOne(new LambdaQueryWrapper<BuMerchant>().eq(BuMerchant::getCreateBy, LoginHelper.getUserId()));
        if (merchant == null) {
            return -1;
        }
        return merchant.getStatus();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean auditByIds(AuditBo bo) {
        List<String> ids = Arrays.asList(bo.getIds().split(","));
        List<BuMerchant> buMerchants = new LambdaQueryChainWrapper<>(baseMapper).in(BuMerchant::getId, ids).list();
        buMerchants.stream().filter(merchant -> merchant.getStatus() == 0).forEach(merchant -> {
            throw new ServiceException("商户【" + merchant.getMerchantName() + "】已审核，请勿重复操作");
        });

        // 添加商户角色
        buMerchants.forEach(merchant ->
            sysUserService.addRoles(merchant.getCreateBy(), RoleConstants.MERCHANT));

        String msg = bo.getStatus() == 0 ? "通过" : "驳回";
        String title = "【" + msg + "】您提交的商户认证已审核" + msg + "，请前往个人中心查看。";

        // 发送站内信
        SseMessageDto dto = new SseMessageDto();
        dto.setMessage(title);
        dto.setUserIds(buMerchants.stream().map(BaseEntity::getCreateBy).collect(Collectors.toList()));
        SseMessageUtils.publishMessage(dto);

        buMerchants.forEach(merchant -> {
            BuMessage buMessage = new BuMessage();
            buMessage.setReceiverId(merchant.getCreateBy());
            buMessage.setTitle(title);
            buMessage.setIsRead(0);
            buMessage.setIsDeleted(0);
            buMessage.setSendTime(new Date());
            buMessage.setBusinessSign("auth");
            buMessageMapper.insert(buMessage);
        });

        return new LambdaUpdateChainWrapper<>(baseMapper)
            .in(BuMerchant::getId, ids)
            .set(BuMerchant::getStatus, bo.getStatus())
            .set(bo.getStatus() == 2, BuMerchant::getReason, bo.getReason())
            .update();
    }

    @Override
    public BuMerchantVo merchantInfo(Long userId) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<BuMerchant>().eq(BuMerchant::getCreateBy, userId));
    }
}
